<template>
  <el-dialog
    v-el-drag-dialog
    title="订单转派"
    :visible.sync="visible"
    width="600px"
    @closed="reset"
  >
    <el-form ref="dataForm" :rules="rules" :model="temp" label-position="right" label-width="90px">
      <el-form-item label="责任机构:" prop="orgId">
        <el-tree-select
          v-model="temp.orgId"
          :clearable="false"
          class="tree-select"
          :popover-width="360"
          :disabled="corpSettingData.sp6 >> 15 & 0x01 || !!temp.relatedDepositCode"
          :select-params="{
            clearable: false,
            placeholder: '请选择',
            loading: $loadingPlugin.getTreeData
          }"
          :tree-params=" {
            'expand-on-click-node': false,
            'highlight-current': true,
            'filterable': true,
            props:{
              value:'orgId',
              label: 'orgName',
              disabled: 'disabled',
            },
            data: treeData
          }"
          @node-click="selectTreeChange"
        />
      </el-form-item>
      <el-form-item label="处理人:" prop="newOwnerId">
        <el-select v-model="temp.newOwnerId" filterable :loading="$loadingPlugin.getOwnersList" style="width: 100%;" placeholder="请选择" @change="chooseOwner">
          <el-option
            v-for="item in ownersList"
            :key="item.userId"
            :label="item.userName"
            :value="item.userId"
          />
        </el-select>
      </el-form-item>
      <el-row :gutter="16">
        <el-col :span="8"><div class="orange">上次配送人员：{{ lastSender }} </div></el-col>
        <el-col :span="8"><div>绑定司机：{{ driverName }} </div></el-col>
        <el-col :span="8"><div>值班人：{{ dutyName }} </div></el-col>
      </el-row>

    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="reset">
        取消
      </el-button>
      <el-button :loading="$loadingPlugin.submit" type="primary" @click="success">
        确定
      </el-button>
    </div>
    <confirmClasses ref="confirmClasses" :parent-fun="reset" />
  </el-dialog>
</template>

<script>
  import { queryOrderTransfer, queryOwnerList, csDeliverUserList, queryLastDispatch, orderDutyCheck } from '@/api'
  import getTreeData from '@/utils/jsonTree'
  import { mapGetters } from 'vuex'
  import confirmClasses from '@/views/components/ConfirmClasses'
  export default {
    name: 'transfer-order',
    components: {
      confirmClasses
    },
    data() {
      return {
        visible: false,
        treeData: [],
        ownersList: [],
        ownerId: '',
        orderCode: '',
        temp: {
          orgId: '',
          newOwnerId: '',
          relatedDepositCode: ''
        },
        lastSender: '无',
        driverName: '',
        dutyName: '',
        rules: {
          orgId: [{ required: true, message: '请选择组织机构', trigger: 'change' }],
          newOwnerId: [{ required: true, message: '请选择处理人', trigger: 'change' }]
        }
      }
    },
    computed: {
      ...mapGetters([
        'orgList', 'corpSettingData'
      ])
    },
    methods: {
      async open(temp) {
        this.ownerId = temp.ownerId
        this.csmAddressId = temp.csmAddressId
        await Promise.all([this.getTreeData(), this.getOwnersListNew(temp.orgId), this.queryLastDispatch()])
        return new Promise(resolve => {
          this.resolve = resolve
          this.visible = true
          if (temp) {
            this.lastSender = '无'
            this.orderCode = temp.orderCode
            this.temp.relatedDepositCode = temp.relatedDepositCode
            this.temp.orgId = temp.orgId
          }
        })
      },
      // 获取上次上次配送人员
      async queryLastDispatch() {
        const res = await queryLastDispatch({ csmAddressId: this.csmAddressId })
        if (res.data) {
          this.lastSender = res.data.lastSender ? res.data.lastSender + '(' + res.data.orgName + ')' : '无'
          this.driverName = res.data.driverName ? res.data.driverName : '无'
          this.dutyName = res.data.dutyName ? res.data.dutyName : '无'
        }
      },
      // 获取责任机构数据
      async getTreeData() {
        const data = this.orgList.map(item => ({
          label: item.name,
          ...item
        }))
        this.treeData = getTreeData(data)
      },
      // 选择所属机构
      selectTreeChange(value) {
        this.temp.orgId = value.orgId
        // this.getOwnersList(value.orgId)
        // 长沙用新接口
        this.getOwnersListNew(value.orgId)
        this.$set(this.temp, 'newOwnerId', '')
      },
      // 查询处理人列表
      async getOwnersList(orgId) {
        const b = this.corpSettingData.sp1 >> 2 & 0x01
        const res = await queryOwnerList({
          orgId,
          corpparm1: b
        })
        this.ownersList = res.data.filter(item => item.userId !== this.ownerId)
      },
      // 查询处理人列表（新）
      async getOwnersListNew(orgId) {
        const res = await csDeliverUserList({ deliveryOrgId: orgId, utype: 32 })
        this.ownersList = res.data.filter(item => item.userId !== this.ownerId)
      },
      async chooseOwner(val) {
        const info = this.ownersList.find(item => item.userId === val)
        if (val) {
          const res = await orderDutyCheck({ ownerId: val, corpSN: info.corpSN })
          if (res.data === 1) {
            this.$refs.confirmClasses.open(info)
          }
        }
      },
      success() {
        this.$refs.dataForm.validate(valid => {
          if (!valid) return
          if (this.temp.newOwnerId === this.ownerId) {
            this.$message.warning('请选择新的处理人')
            return
          }
          const params = { orderCode: this.orderCode, ownerId: this.ownerId, newOwnerId: this.temp.newOwnerId, orgId: this.temp.orgId }
          this.submit(params)
        })
      },
      async submit(params) {
        const res = await queryOrderTransfer(params)
        if (res) {
          this.resolve()
          if (res.data === 2) {
            this.noTransfer()
          } else {
            this.visible = false
            this.$notify({
              title: '提示',
              message: '操作成功!',
              type: 'success',
              duration: 2000
            })
          }
        }
      },
      // 不允许转派
      noTransfer() {
        this.$confirm('支付方式为预付卡的订单，不允许跨站转派', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {

        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
      },
      reset() {
        this.ownerId = ''
        this.orderCode = ''
        this.temp = {
          orgId: '',
          newOwnerId: '',
          relatedDepositCode: ''
        }
        this.$nextTick(() => {
          this.$refs.dataForm.clearValidate()
        })
        this.visible = false
      }
    }
  }
</script>

<style scoped>
  .orange {
    color: #E6A23C;
  }
</style>
